import { Layout, message } from 'antd';
import React, { useEffect } from 'react';
import Menu from "./component/menu"
import styles from "./mainNav.module.scss"
import { Outlet } from "react-router-dom"
import PubSub from 'pubsub-js'
const { Header, Footer, Sider, Content } = Layout;
export let ws

export default function mainNav() {
    function reconnect() {
        // lockReconnect加锁，防止onclose、onerror两次重连
        console.log("正在进行重连");
        // 进行重连
        setTimeout(function () {
            initWebSocket();
        }, 1000);
    }
    function initWebSocket() {
        ws = new WebSocket(`ws:localhost:8000?id=${localStorage.getItem("id")}`);
        ws.onopen = function () {
            console.log("localhost:8000，连接成功");
        };
        ws.onmessage = function (e) {
            let item = JSON.parse(e.data)
            if (item.code === 300) {
                message.success("您有一条新消息请在线在线咨询中查看")
                PubSub.publish("message", item)

            } else if (item.code === 301) {
                PubSub.publish("message", item)
            }

        };
        ws.onclose = function (e) {
            console.log("close")
            reconnect()
        }
    }
    useEffect(() => {
        initWebSocket()
    }, [])
    return (
        <div className={styles.content}>
            <Layout style={{ height: '100%' }}>
                <Sider style={{ boxShadow: '0px 0px 4px 0px rgba(0,0,0,.1)' }}>
                    <Menu></Menu>
                </Sider>
                <Layout>
                    <Content style={{ padding: 30 }}>
                        <Outlet></Outlet>
                    </Content>
                </Layout>
            </Layout>
        </div>

    )
}
